package org.sanguine.study.hometasks.second;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Task5 {
	
	public static class ModelCircuit {
		private List<Double> voltageMeasurements;
		private List<Double> amperageMeasurements;
		
		public ModelCircuit() {
			voltageMeasurements = new ArrayList<>();
			amperageMeasurements = new ArrayList<>();
		}
		
		public ModelCircuit(Collection<Double> voltage, Collection<Double> amperage) {
			this();
			if (voltage != null && amperage != null) {
				int numberOfMeasurements = Math.min(voltage.size(), amperage.size());
				Iterator<Double> iterVoltage = voltage.iterator();
				Iterator<Double> iterAmperage = amperage.iterator();
				while (numberOfMeasurements > 0) {
					voltageMeasurements.add(iterVoltage.next());
					amperageMeasurements.add(iterAmperage.next());
					numberOfMeasurements--;
				}
			}
		}
		
		public Double getResistance() throws IllegalStateException {
			if (voltageMeasurements == null
				|| voltageMeasurements.isEmpty()
				|| amperageMeasurements == null
				|| amperageMeasurements.isEmpty()
				|| voltageMeasurements.size() != amperageMeasurements.size()) throw new IllegalStateException("Measurements must be set properly");
			
			return computeResistance();
		}

		private Double computeResistance() {
			Iterator<Double> iterVoltage = voltageMeasurements.iterator();
			Iterator<Double> iterAmperage = amperageMeasurements.iterator();
			Double ui = 0.0;
			Double i2 = 0.0;
			while (iterAmperage.hasNext()) {
				Double I = iterAmperage.next();
				Double U = iterVoltage.next();
				i2 += I * I;
				ui += I * U;
			}
			return ui / i2;
		}
		
	}

}
